package com.dx.mes.service.query.service;
import static com.dx.mes.common.bean.def.GenericDef.E_BIS_DATA;
import static com.dx.mes.common.bean.def.GenericDef.E_BIS_MTRL;
import static com.dx.mes.common.bean.def.GenericDef.E_FIPINQBOX_INVALID_INPUT;
import static com.dx.mes.common.bean.def.GenericDef.E_READ_NOT_FOUND;
import static com.dx.mes.common.bean.def.GenericDef.E_RET_WO;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_SET_ERROR;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_MESG_OK;
import static com.dx.mes.common.bean.def.GenericDef.TRX_OUT;

import java.util.ArrayList;
import java.util.List;

import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.query.service.IMipwobomService;
import com.dx.mes.facade.query.tx.Mpinqwobom.MipwobomI;
import com.dx.mes.facade.query.tx.Mpinqwobom.MipwobomO;
import com.dx.mes.facade.query.tx.Mpinqwobom.MipwobomOA;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 * Created by ADMIN on 2017/11/2.
 */

@Service("mipwobomService")
public class MipwobomService implements IMipwobomService {
    private LogUtils logUtils;
    private static final String TX_NAME = "MIPWOBOM";
    @Autowired
    private IBisMtrlDao bisMtrlDao;
    @Autowired
    private IRetWoBomDao  retWoBomDao;
    @Autowired
    private IRetWhMtrlDao retWhMtrlDao;
    @Override
    public String subMainProc(String evt_no, String strInMsg) {
        AppContext.clear();
        AppContext.setCurrServiceName(MipwobomService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(MipwobomService.class);
        logUtils.info("[InTrx:" + strInMsg + "]");
        String outMsg = "";

        MipwobomI inTrx = new MipwobomI();
        MipwobomO outTrx = new MipwobomO();

        outTrx.setTrx_id(TX_NAME);
        outTrx.setType_id(TRX_OUT);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

        try {
            inTrx = JacksonUtil.fromJson(strInMsg, MipwobomI.class);

            subMainProc2(inTrx.getAction_flg().toCharArray()[0],inTrx,outTrx);
            if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
                bisMtrlDao.flushCurSession();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } catch (Exception ex) {
            outTrx.setRtn_mesg(ex.toString());
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            logUtils.error(Util.stackTraceToString(ex));
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
        } finally {
            outMsg = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + outMsg + "]");
        }
        return outMsg;
    }

    private void subMainProc2(char actionType,MipwobomI inTrx,   MipwobomO outTrx) {

        switch (actionType) {
            case 'Q': {
                getbomByCondition(inTrx, outTrx);
                break;
            }
            case 'R':{
                getbom(inTrx, outTrx);
                break;
            }
            default: {
                String gszMsgBuf = "Invalide type input: [" + actionType + "]";
                outTrx.setRtn_mesg(gszMsgBuf);
                outTrx.setRtn_code(String.valueOf(E_FIPINQBOX_INVALID_INPUT));
            }
        }
    }

    private void getbomByCondition(MipwobomI inTrx, MipwobomO outTrx) {
        List<MipwobomOA> oary_bom = new ArrayList<MipwobomOA>();
        String sql = "FROM Ret_wo_bom WHERE 1=1";
		if (!Util.isSpaceCheck(inTrx.getWo_id_fk())) {
            sql += " AND wo_id_fk= '"+inTrx.getWo_id_fk()+"'";
        }
        if (!Util.isSpaceCheck(inTrx.getMtrl_prod_id_fk())) {
            sql += " AND mtrl_prod_id_fk='"+inTrx.getMtrl_prod_id_fk()+"'";
		}
        if (!Util.isSpaceCheck(inTrx.getMtrl_cate())) {
            sql += " AND mtrl_cate= '"+inTrx.getMtrl_cate()+"'";
        }

        sql += " order by evt_timestamp asc";

		List<Ret_wo_bom> ret_wo_boms = retWoBomDao.find(sql);
        for(Ret_wo_bom ret_wo_bom : ret_wo_boms){
            String hql = "from Ret_wh_mtrl where mtrl_prod_id_fk='" + ret_wo_bom.getId().getMtrl_prod_id_fk()
            		 + "' and mtrl_cate='" + ret_wo_bom.getId().getMtrl_cate() + "' and dest_shop='" + inTrx.getDest_shop() + "'";
            List<Ret_wh_mtrl> ret_wh_mtrls = retWhMtrlDao.find(hql);
            for(Ret_wh_mtrl ret_wh_mtrl:ret_wh_mtrls){
                Double mtrlWhQty=0.0;
                MipwobomOA oaryA = new MipwobomOA();
                oaryA.setWo_id_fk(ret_wo_bom.getId().getWo_id_fk());
                oaryA.setMtrl_cate(ret_wo_bom.getId().getMtrl_cate());
                oaryA.setMtrl_prod_id_fk(ret_wo_bom.getId().getMtrl_prod_id_fk());
                Bis_mtrl bis_mtrl = bisMtrlDao.get(ret_wh_mtrl.getMtrl_prod_id_fk());
                if(bis_mtrl!=null){
                    oaryA.setMtrl_prod_dsc(bis_mtrl.getMtrl_prod_dsc());
                }else{
                    oaryA.setMtrl_prod_dsc("未知的物料名称");
                }
                oaryA.setMtrl_unit(ret_wo_bom.getMtrl_unit_fk());
                oaryA.setMtrl_use_qty(ret_wo_bom.getMtrl_use_qty());
                oaryA.setOpe_id_fk(ret_wo_bom.getOpe_id_fk());
            	mtrlWhQty += ret_wh_mtrl.getMtrl_qty() - ret_wh_mtrl.getEvt_qty();
            	if(!StringUtils.isEmpty(ret_wh_mtrl.getMtrl_lot_id())){
                    oaryA.setMtrl_lot_id(ret_wh_mtrl.getMtrl_lot_id());
                }
                oaryA.setMtrl_wh_qty(mtrlWhQty);
                oary_bom.add(oaryA);
            }
        }
        outTrx.setOaryA(oary_bom);
        outTrx.setWo_cnt(oary_bom.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
    }
    private void getbom(MipwobomI inTrx, MipwobomO outTrx) {
        List<MipwobomOA> oary_bom = new ArrayList<MipwobomOA>();
        String sql = "FROM Ret_wo_bom WHERE 1=1";
        if (!Util.isSpaceCheck(inTrx.getWo_id_fk())) {
            sql += " AND wo_id_fk= '"+inTrx.getWo_id_fk()+"'";
        }
        if (!Util.isSpaceCheck(inTrx.getMtrl_prod_id_fk())) {
            sql += " AND mtrl_prod_id_fk='"+inTrx.getMtrl_prod_id_fk()+"'";
        }
        if (!Util.isSpaceCheck(inTrx.getMtrl_cate())) {
            sql += " AND mtrl_cate= '"+inTrx.getMtrl_cate()+"'";
        }
        if (!Util.isSpaceCheck(inTrx.getMtrl_type())) {
            sql += " AND mtrl_type= '"+inTrx.getMtrl_type()+"'";
        }
        sql += " order by evt_timestamp asc";
        List<Ret_wo_bom> ret_wo_boms = retWoBomDao.find(sql);
        for(Ret_wo_bom ret_wo_bom : ret_wo_boms){
            MipwobomOA oaryA = new MipwobomOA();
            oaryA.setWo_id_fk(ret_wo_bom.getId().getWo_id_fk());
            oaryA.setMtrl_cate(ret_wo_bom.getId().getMtrl_cate());
            oaryA.setMtrl_prod_id_fk(ret_wo_bom.getId().getMtrl_prod_id_fk());
            oaryA.setMtrl_unit(ret_wo_bom.getMtrl_unit_fk());
            oaryA.setMtrl_use_qty(ret_wo_bom.getMtrl_use_qty());
            oaryA.setOpe_id_fk(ret_wo_bom.getOpe_id_fk());
            oary_bom.add(oaryA);
        }
        outTrx.setOaryA(oary_bom);
        outTrx.setWo_cnt(ret_wo_boms.size());
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
    }
}





